
package com.google.bitcoin.core;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.Collection;

import java.util.Arrays;

/**
 * Separates the keystore functions from the wallet
 */
public class KeyStore implements java.io.Serializable
{
    public final static long serialVersionUID = 2L;
    private HashMap<Address, ECKey> keys;
    protected NetworkParameters params;

    public KeyStore(NetworkParameters params)
    {
        this.params = params;
        keys = new HashMap<Address, ECKey>();
    }

    public void addKey(ECKey key)
    {
        synchronized(keys)
        {
            keys.put(key.toAddress(params), key);
        }
    }
    public Iterable<ECKey> getKeys()
    {
        LinkedList<ECKey> lst = new LinkedList<ECKey>();
        synchronized(keys)
        {
            lst.addAll(keys.values());
        }

        return lst;
    }
    public Collection<Address> getAddresses()
    {
        LinkedList<Address> lst = new LinkedList<Address>();
        synchronized(keys)
        {
            lst.addAll(keys.keySet());
        }

        return lst;

    }

    public synchronized ECKey findKeyFromPubHash(byte[] pubkeyHash) 
    {
        synchronized(keys)
        {
            for (ECKey key : keys.values()) 
            {
                if (Arrays.equals(key.getPubKeyHash(), pubkeyHash)) return key;
            }
        }
        return null;
    }

    public ECKey getKey(Address addr)
    {
        synchronized(keys)
        {
            return keys.get(addr);
        }
    }
    public boolean isAddressMine(Address addr)
    {
        return (getKey(addr) != null);
    }

    public boolean isPubKeyHashMine(byte[] pubkeyHash)
    {
        return (findKeyFromPubHash(pubkeyHash) != null);
    }

    public long getEarliestKeyCreationTime() 
    {
        synchronized(keys)
        {
            if (keys.size() == 0) {
                return Utils.now().getTime() / 1000;
            }
            long earliestTime = Long.MAX_VALUE;
            for (ECKey key : keys.values()) {
                earliestTime = Math.min(key.getCreationTimeSeconds(), earliestTime);
            }
            return earliestTime;
        }
    }

}
